﻿#include "AdminSystem.h"
#include "UserCenterMenuHelper.h"
#include <QToolButton>
#include <QMenu>
#include <QAction>
#include <QMessageBox>
#include <LoginSystem.h>
#include <Global_Class.h>
#include "user_admin.h"
#include "train_admin.h"
#include "StationAdminDialog.h"
#include "ScheduleAdminDialog.h"
#include "SeatAdminDialog.h"
#include "ManualRefundOrChangeDialog.h"
#include "TicketAdminDialog.h"

AdminSystem::AdminSystem(QWidget *parent)
	: QMainWindow(parent)
{
	ui.setupUi(this);

	//// 初始化用户中心菜单相关成员
	//UserCenterToolAction = new QAction(tr("用户中心"), this);
	//userCenterMenu = new QMenu(tr("用户中心"), this);
	//userInfoAction = new QAction(tr("个人信息"), this);
	//logoutAction = new QAction(tr("退出登录"), this);
	//userDeleteAction = new QAction(tr("注销用户"), this);
	//userCenterMenu->addAction(userInfoAction);
	//userCenterMenu->addAction(logoutAction);
	//userCenterMenu->addAction(userDeleteAction);

	//优化用户中心UI版本--------------------------------------------------------------------------------------
	UserCenterToolAction = new QAction(tr("👤 用户中心"), this);
	UserCenterToolAction->setFont(QFont("Microsoft YaHei", 10));
	userCenterMenu = new QMenu(tr("用户中心"), this);
	userCenterMenu->setFont(QFont("Microsoft YaHei", 9));
	userCenterMenu->setStyleSheet(
		"QMenu {"
		"    background-color: white;"
		"    border: 1px solid #e0e0e0;"
		"    border-radius: 8px;"
		"    padding: 8px 0px;"
		"    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);"
		"    color: #2c3e50;"
		"}"
		"QMenu::item {"
		"    padding: 8px 20px;"
		"    border: none;"
		"    font-family: 'Microsoft YaHei';"
		"    font-size: 9pt;"
		"    color: #2c3e50;"
		"    background-color: transparent;"
		"}"
		"QMenu::item:selected {"
		"    background-color: #e3f2fd;"
		"    color: #1565c0;"
		"    border-radius: 4px;"
		"    margin: 2px 8px;"
		"}"
		"QMenu::separator {"
		"    height: 1px;"
		"    background-color: #e0e0e0;"
		"    margin: 4px 12px;"
		"}"
	);

	userInfoAction = new QAction(tr("👤 个人信息"), this);
	userInfoAction->setFont(QFont("Microsoft YaHei", 9));

	logoutAction = new QAction(tr("🚪 退出登录"), this);
	logoutAction->setFont(QFont("Microsoft YaHei", 9));

	userDeleteAction = new QAction(tr("🗑️ 注销用户"), this);
	userDeleteAction->setFont(QFont("Microsoft YaHei", 9));

	userCenterMenu->addAction(userInfoAction);
	userCenterMenu->addSeparator(); 
	userCenterMenu->addAction(logoutAction);
	userCenterMenu->addAction(userDeleteAction);

	userCenterMenu->setWindowFlags(userCenterMenu->windowFlags() | Qt::FramelessWindowHint);
	userCenterMenu->setAttribute(Qt::WA_TranslucentBackground);

	//------------------------------------------------------------------------------------------------------------


	//将useradmin按钮与槽函数连接起来
	connect(ui.useradmin,
		&QPushButton::clicked,
		this,
		[this] {
			onUserManagementToolAction();
		});
	connect(ui.trainadmin,
		&QPushButton::clicked,
		this,
		[this] {
			onTrainManagementToolAction();
		});
	connect(ui.stationAdmin, &QPushButton::clicked, this, &AdminSystem::onStationManagementToolAction);
	connect(ui.scheduleAdmin, &QPushButton::clicked, this, &AdminSystem::onScheduleManagementToolAction);
	connect(ui.seatAdmin, &QPushButton::clicked, this, &AdminSystem::onSeatManagementToolAction); // 新增座位模板管理按钮信号连接
	// 新增手工退改按钮信号连接
	connect(ui.ManualRefundOrChangeAdmin, &QPushButton::clicked, this, []() {
		ManualRefundOrChangeDialog dlg;
		dlg.exec();
	});
	connect(ui.ticketadmin, &QPushButton::clicked, this, &AdminSystem::onTicketManagementToolAction);

	SetupAdminToolBar();

	// 连接用户中心菜单信号到槽
	connect(userInfoAction, &QAction::triggered, this, &AdminSystem::onUserInformationAction);
	connect(logoutAction, &QAction::triggered, this, &AdminSystem::onLogoutAction);
	connect(userDeleteAction, &QAction::triggered, this, &AdminSystem::onUserDeleteAction);
}

AdminSystem::~AdminSystem()
{}

void AdminSystem::SetupAdminToolBar()
{
	UserCenterMenuHelper::SetupUserCenterMenu(
		ui.mainToolBar,
		UserCenterToolAction,
		userCenterMenu
	);
}


//// 用户中心菜单相关槽函数
//void AdminSystem::onUserInformationAction()
//{
//    // 管理员信息展示，直接从 allData->usersQueue 查找管理员账号
//    // 假设管理员登录后，用户名为 admin 或 role 为 admin
//    // 这里以 role == "admin" 的第一个用户为例
//    users* adminUser = nullptr;
//    for (auto& user : allData->usersQueue) {
//        if (user.getRole() == "admin") {
//            adminUser = &user;
//            break;
//        }
//    }
//    if (adminUser) {
//        QString info = QString(
//            "用户ID: %1\n用户名: %2\n昵称: %3\n密码: %4\n手机号: %5\n角色: %6\n身份证: %7")
//            .arg(QString::fromStdString(adminUser->getUserId()))
//            .arg(QString::fromStdString(adminUser->getUsername()))
//            .arg(QString::fromStdString(adminUser->getDisplayName()))
//            .arg(QString::fromStdString(adminUser->getPassword()))
//            .arg(QString::fromStdString(adminUser->getPhone()))
//            .arg(QString::fromStdString(adminUser->getRole()))
//            .arg(QString::fromStdString(adminUser->getIdCard()));
//        QMessageBox::information(this, "管理员信息", info);
//    } else {
//        QMessageBox::warning(this, "管理员信息", "未找到管理员信息。");
//    }
//}

//优化UI后的版本------------------------------------------------------------------------------------------
// 用户中心菜单相关槽函数
void AdminSystem::onUserInformationAction()
{
    // 管理员信息展示，直接从 allData->usersQueue 查找管理员账号
    users* adminUser = nullptr;
    for (auto& user : allData->usersQueue) {
        if (user.getRole() == "admin") {
            adminUser = &user;
            break;
        }
    }

    if (adminUser) {
        // 创建自定义对话框
        QDialog* infoDialog = new QDialog(this);
        infoDialog->setWindowTitle("👤 管理员信息");
        infoDialog->setMinimumSize(450, 400);
        infoDialog->setWindowFlags(infoDialog->windowFlags() & ~Qt::WindowContextHelpButtonHint);

        // 设置对话框样式
        infoDialog->setStyleSheet(R"(
            QDialog {
                background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,
                                          stop: 0 #f5f7fa, stop: 1 #e4e7ec);
                font-family: 'Microsoft YaHei';
            }
            QLabel {
                color: #2c3e50;
                font-size: 10pt;
            }
            QLabel[title="true"] {
                color: #34495e;
                font-size: 12pt;
                font-weight: bold;
                padding: 10px 0px 5px 0px;
            }
            QLabel[field="true"] {
                background-color: white;
                border: 1px solid #e0e0e0;
                border-radius: 6px;
                padding: 8px 12px;
                margin: 2px 0px;
                color: #2c3e50;
                font-size: 9.5pt;
            }
            QPushButton {
                background-color: #3498db;
                color: white;
                border: none;
                border-radius: 6px;
                padding: 8px 16px;
                font-weight: bold;
                min-width: 80px;
                font-size: 9.5pt;
            }
            QPushButton:hover {
                background-color: #2980b9;
            }
            QPushButton:pressed {
                background-color: #3498db;
            }
        )");

        QVBoxLayout* mainLayout = new QVBoxLayout(infoDialog);
        mainLayout->setSpacing(15);
        mainLayout->setContentsMargins(20, 20, 20, 20);

        // 标题
        QLabel* titleLabel = new QLabel("管理员账户信息", infoDialog);
        titleLabel->setProperty("title", true);
        titleLabel->setAlignment(Qt::AlignCenter);
        mainLayout->addWidget(titleLabel);

        // 信息显示区域
        QFrame* infoFrame = new QFrame(infoDialog);
        infoFrame->setStyleSheet("QFrame { background-color: white; border-radius: 8px; }");
        QVBoxLayout* infoLayout = new QVBoxLayout(infoFrame);
        infoLayout->setSpacing(8);
        infoLayout->setContentsMargins(15, 15, 15, 15);

        // 创建信息项
        auto createInfoItem = [infoLayout, infoDialog](const QString& label, const QString& value) {
            QHBoxLayout* itemLayout = new QHBoxLayout();

            QLabel* nameLabel = new QLabel(label + ":", infoDialog);
            nameLabel->setStyleSheet("color: #7f8c8d; font-weight: bold; min-width: 80px;");
            nameLabel->setAlignment(Qt::AlignRight | Qt::AlignVCenter);

            QLabel* valueLabel = new QLabel(value, infoDialog);
            valueLabel->setProperty("field", true);
            valueLabel->setWordWrap(true);
            valueLabel->setMinimumHeight(30);

            itemLayout->addWidget(nameLabel);
            itemLayout->addWidget(valueLabel, 1);
            infoLayout->addLayout(itemLayout);
            };

        // 添加各项信息
        createInfoItem("用户ID", QString::fromStdString(adminUser->getUserId()));
        createInfoItem("用户名", QString::fromStdString(adminUser->getUsername()));
        createInfoItem("显示名称", QString::fromStdString(adminUser->getDisplayName()));
        createInfoItem("手机号", QString::fromStdString(adminUser->getPhone()));
        createInfoItem("角色", QString::fromStdString(adminUser->getRole()));
        createInfoItem("身份证号", QString::fromStdString(adminUser->getIdCard()));

        // 密码项特殊处理（可以添加显示/隐藏功能）
        QHBoxLayout* passwordLayout = new QHBoxLayout();
        QLabel* passwordLabel = new QLabel("密码:", infoDialog);
        passwordLabel->setStyleSheet("color: #7f8c8d; font-weight: bold; min-width: 80px;");
        passwordLabel->setAlignment(Qt::AlignRight | Qt::AlignVCenter);

        QLabel* passwordValue = new QLabel("••••••••", infoDialog);
        passwordValue->setProperty("field", true);
        passwordValue->setMinimumHeight(50);

        QPushButton* showPasswordBtn = new QPushButton("👁️", infoDialog);
        showPasswordBtn->setFixedSize(30, 30);
        showPasswordBtn->setStyleSheet(
            "QPushButton {"
            "    background-color: #95a5a6;"
            "    color: white;"
            "    border: none;"
            "    border-radius: 4px;"
            "    font-size: 10pt;"
            "}"
            "QPushButton:hover {"
            "    background-color: #7f8c8d;"
            "}"
        );

        // 密码显示/隐藏功能
        bool passwordVisible = false;
        connect(showPasswordBtn, &QPushButton::clicked, [passwordValue, adminUser, &passwordVisible]() {
            passwordVisible = !passwordVisible;
            if (passwordVisible) {
                passwordValue->setText(QString::fromStdString(adminUser->getPassword()));
                passwordValue->setStyleSheet(
                    "background-color: #fff3cd;"
                    "border: 1px solid #ffeaa7;"
                    "border-radius: 6px;"
                    "padding: 8px 12px;"
                    "margin: 2px 0px;"
                    "color: #856404;"
                    "font-size: 9.5pt;"
                );
            }
            else {
                passwordValue->setText("••••••••");
                passwordValue->setStyleSheet(
                    "background-color: white;"
                    "border: 1px solid #e0e0e0;"
                    "border-radius: 6px;"
                    "padding: 8px 12px;"
                    "margin: 2px 0px;"
                    "color: #2c3e50;"
                    "font-size: 9.5pt;"
                );
            }
            });

        passwordLayout->addWidget(passwordLabel);
        passwordLayout->addWidget(passwordValue, 1);
        passwordLayout->addWidget(showPasswordBtn);
        infoLayout->addLayout(passwordLayout);

        mainLayout->addWidget(infoFrame);

        // 按钮区域
        QHBoxLayout* buttonLayout = new QHBoxLayout();
        buttonLayout->setSpacing(10);
        QPushButton* closeBtn = new QPushButton("✅ 关闭", infoDialog);

        buttonLayout->addStretch();
        buttonLayout->addWidget(closeBtn);

        mainLayout->addLayout(buttonLayout);

        // 连接信号
        connect(closeBtn, &QPushButton::clicked, infoDialog, &QDialog::accept);

        // 显示对话框
        infoDialog->exec();
        delete infoDialog;

    }
    else {
        // 错误提示也美化
        QMessageBox msgBox(this);
        msgBox.setWindowTitle("⚠️ 信息提示");
        msgBox.setText("未找到管理员信息");
        msgBox.setIcon(QMessageBox::Warning);
        msgBox.setStyleSheet(
            "QMessageBox {"
            "    background-color: white;"
            "    font-family: 'Microsoft YaHei';"
            "}"
            "QMessageBox QPushButton {"
            "    background-color: #3498db;"
            "    color: white;"
            "    border: none;"
            "    border-radius: 4px;"
            "    padding: 6px 12px;"
            "    min-width: 60px;"
            "}"
            "QMessageBox QPushButton:hover {"
            "    background-color: #2980b9;"
            "}"
        );
        msgBox.exec();
    }
}
//---------------------------------------------------------------------------------------------------------

void AdminSystem::onLogoutAction()
{
	/*QMessageBox::StandardButton reply;
	reply = QMessageBox::question(this, "Logout", "确定要退出登录吗？", QMessageBox::Yes | QMessageBox::No);*/

    //优化后UI-----------------------------------------------------------------------------------------------------
   
    QMessageBox logoutBox(this);
    logoutBox.setWindowTitle("🚪 退出登录");
    logoutBox.setText("<h3 style='color: #2c3e50; margin: 10px 0;'>确认退出登录</h3>");
    logoutBox.setInformativeText("<p style='color: #7f8c8d; font-size: 10pt; margin: 15px 0;'>"
        "您确定要退出当前账号吗？退出后需要重新登录。</p>");

    // 设置图标（使用自定义图标或系统图标）
    logoutBox.setIconPixmap(QPixmap(":/icons/logout.png").scaled(48, 48, Qt::KeepAspectRatio, Qt::SmoothTransformation));
    // 或者使用标准图标
    // logoutBox.setIcon(QMessageBox::Question);

    // 自定义按钮
    QPushButton* confirmBtn = logoutBox.addButton("✅ 确认退出", QMessageBox::YesRole);
    QPushButton* cancelBtn = logoutBox.addButton("❌ 取消", QMessageBox::NoRole);

    // 设置对话框样式
    logoutBox.setStyleSheet(R"(
    QMessageBox {
        background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,
                                  stop: 0 #f5f7fa, stop: 1 #e4e7ec);
        border: 1px solid #d1d9e6;
        border-radius: 12px;
        font-family: 'Microsoft YaHei';
    }
    QMessageBox QLabel {
        color: #2c3e50;
        font-size: 10pt;
    }
    QMessageBox QLabel#qt_msgbox_label {
        min-width: 300px;
        min-height: 60px;
    }
    QMessageBox QPushButton {
        background-color: #3498db;
        color: white;
        border: none;
        border-radius: 6px;
        padding: 8px 16px;
        font-weight: bold;
        min-width: 100px;
        min-height: 32px;
        font-size: 9.5pt;
        margin: 5px;
    }
    QMessageBox QPushButton:hover {
        background-color: #2980b9;
        transform: translateY(-1px);
    }
    QMessageBox QPushButton:pressed {
        background-color: #3498db;
        transform: translateY(0);
    }
    QMessageBox QPushButton[text="✅ 确认退出"] {
        background-color: #e74c3c;
    }
    QMessageBox QPushButton[text="✅ 确认退出"]:hover {
        background-color: #c0392b;
    }
    QMessageBox QPushButton[text="❌ 取消"] {
        background-color: #95a5a6;
    }
    QMessageBox QPushButton[text="❌ 取消"]:hover {
        background-color: #7f8c8d;
    }
)");

    // 设置窗口标志，去除帮助按钮
    logoutBox.setWindowFlags(logoutBox.windowFlags() | Qt::MSWindowsFixedSizeDialogHint);
    logoutBox.setWindowFlags(logoutBox.windowFlags() & ~Qt::WindowContextHelpButtonHint);

    // 显示对话框并获取结果
    logoutBox.exec();

    QMessageBox::StandardButton reply = QMessageBox::No; // 默认值
    if (logoutBox.clickedButton() == confirmBtn) {
        reply = QMessageBox::Yes;
    }
    else {
        reply = QMessageBox::No;
    }
	//------------------------------------------------------------------------------------------------------------


	if (reply == QMessageBox::Yes) {
		this->close();
		//ADD refreshdata
		allData->Order_WriteToFile("littleTerm_Data/orders.txt");
		allData->SeatOccupy_WriteToFile("seat_occupy.txt");
		allData->Seat_WriteToFile("littleTerm_Data/seats.txt");
		allData->Station_WriteToFile("littleTerm_Data/stations.txt");
		allData->Train_Schedeles_WriteToFile("littleTerm_Data/train_schedule.txt");
		allData->Train_WriteToFile("littleTerm_Data/trains.txt");
		allData->User_WriteToFile("littleTerm_Data/users.txt");
		LoginSystem* loginWindow = new LoginSystem();
		loginWindow->initLoginSystem();
		loginWindow->show();
	}
}

void AdminSystem::onUserDeleteAction()
{
	/*QMessageBox::information(this, "注销", "管理员账号不支持注销。");*/
    QMessageBox infoBox(this);
    infoBox.setWindowTitle("账号提示");
    infoBox.setText("管理员账号不支持注销");
    infoBox.setInformativeText("管理员账号为系统核心账户，出于安全考虑不支持注销操作。");
    infoBox.setIcon(QMessageBox::Information);
    infoBox.setStandardButtons(QMessageBox::Ok);
    QPushButton* acknowledgeButton = infoBox.addButton("✅ 我知道了", QMessageBox::AcceptRole);

    // 设置基础样式
    infoBox.setStyleSheet(R"(
    QMessageBox {
        background-color: white;
        border: 1px solid #e0e0e0;
        border-radius: 8px;
        font-family: 'Microsoft YaHei';
    }
    QMessageBox QLabel {
        color: #2c3e50;
    }
    QMessageBox QPushButton {
        background-color: #3498db;
        color: white;
        border: none;
        border-radius: 4px;
        padding: 6px 12px;
        min-width: 80px;
    }
    QMessageBox QPushButton:hover {
        background-color: #2980b9;
    }
)");

    infoBox.exec();
}

void AdminSystem::onUserManagementToolAction()
{
	user_admin* userAdmin = new user_admin(this);
	userAdmin->show();
	return;
}

void AdminSystem::onTrainManagementToolAction()
{
	train_admin* trainAdmin = new train_admin(this);
	trainAdmin->show();
	return;
}

void AdminSystem::onStationManagementToolAction()
{
	StationAdminDialog* dlg = new StationAdminDialog(this);
	dlg->exec();
	delete dlg;
}

void AdminSystem::onScheduleManagementToolAction()
{
	ScheduleAdminDialog* dlg = new ScheduleAdminDialog(this);
	dlg->exec();
	delete dlg;
}

void AdminSystem::onSeatManagementToolAction()
{
	SeatAdminDialog* dlg = new SeatAdminDialog(this);
	dlg->exec();
	delete dlg;
}

void AdminSystem::onTicketManagementToolAction()
{
    TicketAdminDialog* dlg = new TicketAdminDialog(this);
    dlg->exec();
    delete dlg;
}